package com.tao.orders.api;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.tao.base.model.Result;
import com.tao.base.utils.SecurityUtil;
import com.tao.orders.config.AlipayConfig;
import com.tao.orders.model.dto.AddOrderDto;
import com.tao.orders.model.dto.PayRecordDto;
import com.tao.orders.model.dto.PayStatusDto;
import com.tao.orders.model.po.PayRecord;
import com.tao.orders.service.OrderService;
import com.tao.orders.service.impl.OrderServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * <p>
 * 订单服务接口层
 * </p>
 *
 * @author taohongrun
 * @since 2024/11/29
 */
@Tag(name = "订单服务接口层")
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Value("${pay.alipay.APP_ID}")
    String APP_ID;
    @Value("${pay.alipay.APP_PRIVATE_KEY}")
    String APP_PRIVATE_KEY;
    @Value("${pay.alipay.ALIPAY_PUBLIC_KEY}")
    String ALIPAY_PUBLIC_KEY;
    @Value("${pay.notifyHost}")
    String notifyHost;
    @Autowired
    OrderServiceImpl orderService;

    @Operation(summary = "生成支付二维码")
    @PostMapping("/generatePayCode")
    public Result<PayRecordDto> generatePayCode(@RequestBody AddOrderDto addOrderDto) {

        SecurityUtil.User user = SecurityUtil.getUser();
        PayRecordDto order = orderService.createOrder(user.getId(), addOrderDto);
        return Result.success(order);
    }

    @Operation(summary = "唤起支付宝进行支付")
    @GetMapping("/wakeupAlipay")
    public void wakeupAlipay(HttpServletRequest httpRequest,
                             HttpServletResponse httpResponse, String payNo) throws ServletException, IOException, AlipayApiException {
        //payNo可能不存在（数据库删除，缓存未删除）
        orderService.exitPayNo(payNo);

        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, APP_ID, APP_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
        //获得初始化的AlipayClient
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
//        alipayRequest.setReturnUrl("http://domain.com/CallBack/return_url.jsp");
        alipayRequest.setNotifyUrl(notifyHost+"/orders/order/receivenotify");//在公共参数中设置回跳和通知地址
        alipayRequest.setBizContent(orderService.getBizContent(payNo));//填充业务参数
        String form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        httpResponse.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
    }

    @Operation(summary = "判断是否支付成功")
    @GetMapping("/payresult")
    public Result<PayRecordDto> payresult(String payNo) throws IOException {
        //查询支付结果
        PayRecordDto payRecordDto = orderService.queryPayResult(payNo);
        return Result.success(payRecordDto);
    }

    @Operation(summary = "接收支付结果通知")
    @PostMapping("/receivenotify")
    public void receivenotify(HttpServletRequest request, HttpServletResponse out) throws UnsupportedEncodingException, AlipayApiException {
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        //验签
        boolean verify_result = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, "RSA2");

        if (verify_result) {//验证成功

            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
            //appid
            String app_id = new String(request.getParameter("app_id").getBytes("ISO-8859-1"), "UTF-8");
            //total_amount
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            //交易成功处理
            if (trade_status.equals("TRADE_SUCCESS")) {

                PayStatusDto payStatusDto = new PayStatusDto();
                payStatusDto.setOut_trade_no(out_trade_no);
                payStatusDto.setTrade_status(trade_status);
                payStatusDto.setApp_id(app_id);
                payStatusDto.setTrade_no(trade_no);
                payStatusDto.setTotal_amount(total_amount);

                //处理逻辑。。。
                orderService.saveAliPayStatus(payStatusDto);

            }
        }
    }

}
